<template>
  <div class="event-btn-group">
    <template v-if="workEvent.isDelete == 0">
      <div class="flex-1">
        <template v-if="workEvent.inApprove != 1 && workEvent.isPaused != 1">
          <el-button v-if="canEdit" type="plain-third" @click="editEvent" v-track="getBtnsTrackData('TO_EDIT')">
            <i class="iconfont icon-edit-square"></i>{{$t('common.base.edit')}}
          </el-button>
          <!-- <el-tooltip v-if="canEdit" :popper-options="popperOptions" content="编辑事件" placement="top">
            <i class="iconfont icon-edit-square icon-btn" @click="editEvent"></i>
          </el-tooltip> -->
        </template>
        <template v-if="workEvent.isPaused != 1">
          <el-button v-if="canDelete && canEdit" type="plain-third" @click="deleteEvent" v-track="getBtnsTrackData('DELETE')">
            <i class="iconfont icon-delete"></i>{{$t('common.base.delete')}}
          </el-button>
          <!-- <el-tooltip v-if="canEdit" :popper-options="popperOptions" content="删除事件" placement="top">
            <i class="iconfont icon-delete icon-btn" @click="deleteEvent"></i>
          </el-tooltip> -->
        </template>
        <template v-if="CASE_ADD">
          <el-button v-if="canCopyEvent" type="plain-third" @click="copyEvent" v-track="getBtnsTrackData('COPY')">
            <i class="iconfont icon-file-copy"></i>{{$t('common.base.copy')}}
          </el-button>
          <!-- <plink-tooltip v-if="canCopyEvent" :popper-options="popperOptions" content="复制事件" placement="top">
            <i class="iconfont icon-file-copy icon-btn" @click="copyEvent"></i>
          </plink-tooltip> -->
        </template>
        <!-- 亚码芬定制打印 -->
        <template v-if="showAmerPrint">
          <el-button type="plain-third" @click="amerPrintEvent">
            <i class="iconfont icon-printer"></i>{{$t('common.base.print')}}
          </el-button>
        </template>
      </div>
      <template v-if="workEvent.inApprove != 1">
        <!-- 取消事件 -->
        <el-button type="plain-third" v-if="eventOffEvent" @click="offEvent" v-track="getBtnsTrackData('CANCEL')">{{$t('common.base.cancel')}}</el-button>
        <!-- 继续 -->
        <el-button v-if="eventContinue" type="primary" @click="unPauseEvent" v-track="getBtnsTrackData('CONTINUE_EVENT')">{{$t('common.base.continue')}}</el-button>
        <!-- 暂停 -->
        <el-button v-if="eventPause" type="plain-third" @click="pauseEvent" v-track="getBtnsTrackData('PAUSE_EVENT')">{{$t('common.base.usualStatus.paused')}}</el-button>
        <template v-if="showMyBtn && workEvent.isPaused != 1">
          <!-- 开始 -->
          <el-button v-if="workEvent.state == 'allocated' && eventType.flowSetting.start.state" type="primary" @click="startEvent" v-track="getBtnsTrackData('START_EVENT')">{{$t('common.base.start')}}</el-button>
          <!-- 完成事件 -->
          <el-button v-if="(workEvent.state == 'allocated' || workEvent.state == 'processing') && !eventType.flowSetting.start.state" type="primary" @click="finishEvent">{{$t('event.setting.constant.flow_map.name4')}}</el-button>
          <el-button v-if="workEvent.state == 'processing' && eventType.flowSetting.start.state" type="primary" @click="finishEvent">{{$t('event.setting.constant.flow_map.name4')}}</el-button>
        </template>
        <!-- 创建工单 -->
        <template v-if="_isShowEventConvertTask">
          <el-button v-if="eventConvertTask && !eventConvertTaskAndFinishEvent" type="primary" @click="convert2TaskNew('create')">{{$t('common.base.createTask')}}</el-button>
          <el-popover v-if="eventConvertTaskAndFinishEvent" v-model="creatTaskVisible" trigger="click" placement="top-end">
            <el-button type="primary" slot="reference">{{$t('common.base.createTask')}}</el-button>
            <ul>
              <li @click="convert2TaskNew('create')">{{$t('common.base.createTask')}}</li>
              <li @click="convert2TaskNew('finished')">{{$t('event.detail.components.eventButtonGroup.text3')}}</li>
            </ul>
          </el-popover>
        </template>
      </template>

      <!-- 分配 -->
      <el-popover v-if="showAssignButton" trigger="click" placement="top-end">
        <el-button type="primary" slot="reference">{{$t('common.base.distribution')}}</el-button>
        <ul>
          <li @click="editExecutor('allot')" v-track="getBtnsTrackData('MANUAL_DISPATCH')">{{$t('common.event.actionStatus.manualDispatch')}}</li>
          <li v-if="ssConfig.autoDispatchEnabled" @click="autoDispatch" v-track="getBtnsTrackData('AUTO_DISPATCH')">{{$t('common.event.actionStatus.autoDispatch')}}</li>
        </ul>
      </el-popover>
      <template v-if="edit">
        <!-- 转派 -->
        <el-button v-if="workEvent.isPaused != 1 && workEvent.inApprove != 1 && (workEvent.state == 'allocated' || workEvent.state == 'processing')" type="primary" @click="editExecutor('reAllot')" v-track="getBtnsTrackData('EVENT_RE_ALLOT')">{{$t('common.event.actionStatus.redeploy')}}</el-button>
      </template>
      <!-- 高级审批 -->
      <template v-if="unFinishedAppr && unFinishedAppr.processorInstanceId">
        <el-button
          v-for="(item, index) in approveButtonData"
          :key="`${index}_approve`"
          :type="item.type"
          @click="item.event">
          {{ item.name }}
        </el-button>
      </template>
      <template v-else>
        <!-- 审批 -->
        <!-- <el-button v-if="workEvent.inApprove == 1 && unFinishedAppr && unFinishedAppr.id && canApprove" type="primary" @click="approveThis" v-track="getBtnsTrackData('APPROVE_EVENT')">{{$t('common.base.approve')}}</el-button> -->
        <el-button v-if="workEvent.inApprove == 1 && unFinishedAppr && unFinishedAppr.id && canApprove" type="danger" @click="approveThis('refuse')" v-track="getBtnsTrackData('APPROVE_EVENT')">{{$t('common.base.refuse')}}</el-button>
        <el-button v-if="workEvent.inApprove == 1 && unFinishedAppr && unFinishedAppr.id && canApprove"  type="primary" @click="approveThis('agree')" v-track="getBtnsTrackData('APPROVE_EVENT')">{{$t('common.base.agree')}}</el-button>
      </template>
      <!-- 撤回审批 -->
      <el-button v-if="workEvent.inApprove == 1 && unFinishedAppr && unFinishedAppr.id && canOffAppr" type="primary" @click="offApprove" v-track="getBtnsTrackData('WITHDRAW_APPROVE_EVENT')">{{$t('common.task.button.offApprove')}}</el-button>
      <!-- 回退 -->
      <el-button v-if="canEdit && ssConfig.eventRollBack && workEvent.inApprove != 1 && workEvent.state == 'finished' && workEvent.evaluateTime == null" @click="rollBack" v-track="getBtnsTrackData('ROLLBACK_EVENT')">{{$t('common.task.exceptionStatus.rollback')}}</el-button>
      <!-- 添加备注 -->
      <el-button v-if="caseView" type="primary" @click="updataRemarks" v-track="getBtnsTrackData('ADD_REMARKS')">{{$t('common.base.addRemark')}}</el-button>
      <!-- 邮件分享  -->
      <el-button v-if="showEventEmailShare" type="primary" @click="eShareClick" v-track="getBtnsTrackData('EMAIL_SHARE')">{{$t('event.detail.components.eventButtonGroup.text5')}}</el-button>

    </template>
    <div v-else class="has-been-deleted">[{{$t('common.base.deleted')}}]</div>

    <!-- 事件取消弹窗 -->
    <event-off-dialog ref="eventOffDialog" :work-event="workEvent" :getVipApproveFunction="getVipApproveInfo" @success="reloadTab" @needApprove="needApprove" @needVipApprove="toNeedVipApprove"></event-off-dialog>
    <!-- 事件暂停弹窗 -->
    <event-pause-dialog ref="eventPauseDialog" :work-event="workEvent" :getVipApproveFunction="getVipApproveInfo" @needApprove="needApprove" @needVipApprove="toNeedVipApprove"></event-pause-dialog>
    <!-- 事件审批弹窗 -->
    <event-approve-dialog ref="eventApproveDialog" :approve-id="unFinishedAppr && unFinishedAppr.id" :event-id="workEvent.id"></event-approve-dialog>
    <!-- 事件需要审批弹窗 -->
    <event-need-approve-dialog ref="eventNeedApproveDialog" :remark-required="approveRemark" :event-id="workEvent.id" @success="refreshTab" :event-no="workEvent.eventNo"></event-need-approve-dialog>
    <!-- 事件添加备注弹窗 -->
    <event-add-remarks-dialog ref="eventAddRemarksDialog" :work-event="workEvent" :remark-list="remarkList" :message-config="messageConfig" ></event-add-remarks-dialog>
    <!-- 事件回退弹窗 -->
    <event-roll-back-dialog ref="eventRollBackDialog" :work-event="workEvent" @success="reloadTab"></event-roll-back-dialog>
    <!-- 保存到现有客户弹窗 -->
    <save-to-exist-customer-dialog ref="saveToExistCustomerDialog" :work-event="workEvent" :is-address-allow-null="isAddressAllowNull" @success="saveExistCusSuccess"></save-to-exist-customer-dialog>
    <edit-point-dialog ref="editPointDialog" :work-event="workEvent" @onlySaveCusInfo="onlySaveCusInfo"></edit-point-dialog>
    <!-- 保存联系人弹窗 -->
    <event-save-linkman-dialog ref="eventSaveLinkman" :phone-unique="phoneUnique" :work-event="workEvent" @success="refreshTab"></event-save-linkman-dialog>

    <!-- 维护客户信息弹窗 -->
    <base-modal :show.sync="cusMatchDispVisible" :title="$t('event.detail.components.eventButtonGroup.text11')" width="500px" class="cus-match-dispatcher-dialog">
      <div class="base-modal-content">
        <p>
          {{$t('event.detail.components.eventButtonGroup.text7')}}
          <strong>{{$t('event.detail.components.eventButtonGroup.text8')}}</strong>
        </p>
      </div>
      <div slot="footer">
        <el-button type="primary" :loading="save2NewCustomerLoading" @click="save2NewCustomer">{{$t('event.detail.components.eventButtonGroup.text9')}}</el-button>
        <el-button type="primary" @click="save2ExistCustomer">{{$t('event.detail.components.eventButtonGroup.text10')}}</el-button>
      </div>
    </base-modal>
    <!-- 邮件分享弹窗 -->
    <email-sharing-dialog v-if="showEventEmailShare" :work-event="workEvent" ref="EmailSharingDialog"></email-sharing-dialog>
    <!--  高级审批  -->
    <AdvancedApprovalDialog
      :bizNo="workEvent.eventNo"
      :objId="workEvent.id"
      :remark-required="approveRemark"
      ref="AdvancedApprovalDialogRef"
      @success="refreshTab"
    />
  </div>
</template>

<script>
import AuthUtil from '@src/util/auth';
/* api*/
import * as EventApi from '@src/api/EventApi.js';
import { getMailSetting } from '@src/api/EmailApi.ts'
import {checkEventNeedVipApprove} from "@src/api/EventApi.js";
/* components*/
import EventOffDialog from './Dialog/EventOffDialog'
import EventPauseDialog from './Dialog/EventPauseDialog'
import EventNeedApproveDialog from './Dialog/EventNeedApproveDialog'
import EventApproveDialog from './Dialog/EventApproveDialog'
import EventAddRemarksDialog from './Dialog/EventAddRemarksDialog'
import EventRollBackDialog from './Dialog/EventRollBackDialog'
import SaveToExistCustomerDialog from './Dialog/SaveToExistCustomerDialog'
import EditPointDialog from './Dialog/EditPointDialog'
import EventSaveLinkmanDialog from './Dialog/EventSaveLinkmanDialog'
import EmailSharingDialog from './Dialog/EmailSharingDialog.vue'
import AdvancedApprovalDialog from 'src/component/compomentV2/AdvancedApproval/AdvancedApprovalDialog.vue'
/* ennum*/
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
import { chooseExUser } from '@model/config/SelectUserConfig.ts'
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { getRootWindow } from '@src/util/dom'
import { AmerPrintEventTemplateListA, AmerPrintEventTemplateListB, AmerPrintEventTemplateListC} from '@model/enum/EventEnum.ts'
/* version control mixin */
import { VersionControlEventMixin } from '@src/mixins/versionControlMixin'
/* util*/
import { isNotEmpty } from 'pub-bbx-utils'

export default {
  name: 'event-button-group',
  mixins: [VersionControlEventMixin],
  components:{
    EventOffDialog,
    EventPauseDialog,
    EventApproveDialog,
    EventNeedApproveDialog,
    EventAddRemarksDialog,
    EventRollBackDialog,
    SaveToExistCustomerDialog,
    EditPointDialog,
    EventSaveLinkmanDialog,
    EmailSharingDialog,
    AdvancedApprovalDialog,
  },
  props:{
    initData: {
      type: Object,
      default: () => ({})
    },
    workEvent: {
      type: Object,
      default: () => ({})
    },
    auth: {
      type: Object,
      default: () => ({})
    },
    showAssignButton: { // 允许展示分配按钮
      type: Boolean,
      default: false
    },
    // 高级审批按钮信息
    vipApproveSetting: {
      type: Object,
      default: () => ({})
    },
  },
  computed: {
    // 事件未完成
    isAwaiting(){
      return ['allocated', 'processing', 'created'].indexOf(this.workEvent.state) >= 0;
    },
    /**
     * @description: 是否显示分配按钮  有两处用到这个权限 所以迁移到EventDetailView中了
     * 是否拥有事件分配权限
     * workEvent 取值是来自initData里面的 workEvent
     * 事件未完成 isAwaiting
     * 事件不在审批中 inApprove != 1 
     * 事件不是暂停状态 isPaused != 1 
     * 是否有编辑权限 this.canEdit
     * 该事件不存在负责人 this.workEvent.executorId
     * 此处改动是为了修复 bug 17739 和移动端对齐
     * @return {Boolean} 
    */
    // showAssignButton(){
    //   return this.caseAllot && this.isAwaiting && this.workEvent.inApprove != 1 && this.workEvent.isPaused != 1 && this.canEdit && !this.workEvent.executorId
    // },

    /* 是否可以查看客户详情 */
    canSeeCustomer() {
      return this.initData.canSeeCus;
    },
    canPause() {
      return this.initData.canPause;
    },
    showMyBtn() {
      return this.initData.showMyBtn;
    },
    eventType() {
      return this.initData.eventType;
    },
    unFinishedAppr() {
      return this.initData.unFinishedAppr;
    },
    canApprove() {
      return this.initData.canApprove;
    },
    canOffAppr() {
      return this.initData.canOffAppr;
    },
    ssConfig() {
      return this.initData.ssConfig;
    },
    loginUser() {
      return this.initData.loginUser;
    },
    canEdit() {
      return this.initData.canEdit;
    },
    canCopyEvent() {
      return this.initData.canCopyEvent;
    },
    /* 是否拥有事件查看权限 */
    caseView() {
      return this.initData.caseView;
    },
    /* 是否拥有事件编辑权限 */
    edit() {
      return this.initData.edit;
    },
    cusMatchMap() {
      return this.initData.cusMatchMap;
    },
    receiptFields() {
      return this.initData.receiptFields;
    },
    remarkList() {
      return this.initData.remarkList || [];
    },
    approveRemark() {
      return this.initData.ssConfig ? this.initData.ssConfig.approveRemark : false
    },
    isAddressAllowNull() {
      return this.initData.isAddressAllowNull
    },
    messageConfig() {
      return this.initData.messageConfig;
    },
    CASE_EDIT() {
      return AuthUtil.hasAuth(this.auth, 'CASE_EDIT')
    },
    TASK_ADD() {
      return AuthUtil.hasAuth(this.auth, 'TASK_ADD')
    },
    CASE_ADD() {
      return AuthUtil.hasAuth(this.auth, 'CASE_ADD')
    },
    CASE_DELETE() {
      return AuthUtil.hasAuth(this.auth, 'CASE_DELETE')
    },
    SERVICE_ORDER_DELETE() {
      return AuthUtil.hasAuth(this.auth, 'SERVICE_ORDER_DELETE')
    },
    CUSTOMER_CREATE() {
      return AuthUtil.hasAuth(this.auth, 'CUSTOMER_CREATE')
    },
    // 是否开启联系人唯一
    phoneUnique() {
      return this.initData.phoneUnique
    },
    // 事件暂停权限
    eventPause() {
      return this.initData.eventButtonAuths.eventPause.canShow;
    },
    // 事件继续权限
    eventContinue() {
      return this.initData.eventButtonAuths.eventContinue.canShow;
    },
    // 事件转工单权限
    eventConvertTask() {
      return this.initData.eventButtonAuths.eventConvertTask.canShow;
    },
    // 事件转工单并完成事件权限
    eventConvertTaskAndFinishEvent() {
      return this.initData.eventButtonAuths.eventConvertTaskAndFinishEvent.canShow;
    },
    isEventOrder() {
      // TODO: 中文判断
      return this.initData?.eventType?.name == '服务订单'
    },
    canDelete() {
      if (this.isEventOrder) {
        return this.SERVICE_ORDER_DELETE
      }
      
      return this.CASE_DELETE
    },
    // 事件取消权限
    eventOffEvent() {
      return this.initData.eventButtonAuths.eventOffEvent.canShow;
    },
    // 是否显示亚码芬打印
    showAmerPrint() {
      const RootWindow = getRootWindow(window);
      const gray = RootWindow?.grayAuth?.AMER_PRINT ?? false;

      const haveTemplate = [...AmerPrintEventTemplateListA, ...AmerPrintEventTemplateListB, ...AmerPrintEventTemplateListC].includes(this.workEvent?.templateName)
      return gray && haveTemplate
    },
    /**
     * @description 是否显示高级审批设置相关按钮
     * 1. 是审批状态
     * 2.有审批id
     * 3. 且 当前事件是否存在高级审批unFinishedAppr.processorInstanceId
     */
    allowVipApprove() {
      return this.workEvent.inApprove == 1 &&
          isNotEmpty(this.unFinishedAppr?.id) &&
          isNotEmpty(this.unFinishedAppr?.processorInstanceId)
    },
  },
  data() {
    return {
      popperOptions: {
        boundariesElement: 'viewport',
        removeOnDestroy: true
      },
      approveData: {},
      toTaskFlow: '',
      cusInfoSaveTarget: 'convert',
      cusMatchDispVisible: false,
      save2NewCustomerLoading: false,
      cusExist: false,
      creatTaskVisible: false,
      isConvert2Task: false,
      showEventEmailShare:false,
      approveButtonData: [], // 高级审批按钮
    }
  },
  mounted(){
    this.getMailSetting()
  },
  methods: {
    buildApprovalButtonData() {
      // 高级审批按钮
      if(!this.allowVipApprove) return;

      this.approveButtonData = []
      this.vipApproveSetting?.buttons?.forEach((item) =>{
        this.approveButtonData.push({
          name: this.setNameLanguage(item.nameLanguage),
          enName: item.enName,
          type: item.enName == 'agree' ? 'primary' : 'danger',
          event: () => {
            this.$refs.eventApproveDialog.openDialog(item.enName);
          }
        })
      }) ?? []
    },
    setNameLanguage(nameLanguage) {
      let laEnv = this.$i18n.locale ;
      return nameLanguage[laEnv]
    },
    reloadTab() {
      let fromId = window?.frameElement?.getAttribute('fromid')
      this.$platform.refreshTab(fromId)
    },
    closeCurrentTab() {
      const id = window.frameElement?.dataset?.id;
      this.$platform.closeTab(id);
    },

    needApprove(data) {
      this.approveData = data
      this.$refs.eventNeedApproveDialog.openDialog(data)
    },
    
    // 编辑事件
    editEvent() {
      const {isCusExist, isLmExist, isAddExist} = this.cusMatchMap
      let hasCusCreate = undefined;
      if(this.CUSTOMER_CREATE) {
        hasCusCreate = true
      }

      if((isCusExist && isLmExist && isAddExist) || !hasCusCreate) {
        let fromId = window.frameElement.getAttribute('id');
        openAccurateTab({
          type:PageRoutesTypeEnum.PageEditEvent,
          key:this.workEvent.id,
          closeNowPage:true,
          fromId
        })
        // window.location.href = `${this.$resourcePrefix}/event/edit/${this.workEvent.id}`;
      } else {
        this.$refs.editPointDialog.openDialog()
      }
    },

    // 删除事件
    deleteEvent() {
      this.$confirm(this.$t('common.base.tip.areYouSureYouWantDeletIt2'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(() => {
          const params = [`${this.workEvent.id }`]
          EventApi.eventDelete(params).then((res) => {
            if (res.status === 1) {
              this.$notify({
                title: this.$t('common.base.error'),
                message: res.message,
                type: 'error'
              });
            } else {
              this.reloadTab()
              this.closeCurrentTab()
            }
          });
        })
        .catch(() => { });
    },

    // 取消事件 打开弹窗
    offEvent() {
      this.$refs.eventOffDialog.openDialog()
    },

    // 继续事件
    unPauseEvent() {
      const params = {
        id: this.workEvent.id
      }
      EventApi.eventUnPause(params)
        .then(res => {
          if(res.status == 0) {
            window.location.href = `${this.$resourcePrefix}/event/view/${this.workEvent.id}`
          } else {
            this.$notify({
              title: this.$t('common.base.error'),
              message: res.message,
              type: 'error'
            });
          }
        })
    },

    // 暂停事件
    pauseEvent() {
      this.$refs.eventPauseDialog.openDialog()
    },

    // 开始事件
    startEvent() {
      const params = {
        id: this.workEvent.id,
        flow: 'start'
      }
      EventApi.eventCheckNotNullForCard(params)
        .then(async result => {
          if (result.status == 0) {

            const params = {id: `${this.workEvent.id }`}
            // 判断是否有高级审批
            if (await this.checkNeedVipApprove('start', params)) return;

            EventApi.eventStart(params)
                .then(res => {
                  if (res.status == 0) {
                    this.reloadTab();
                    window.location.href = `${this.$resourcePrefix}/event/view/${this.workEvent.id}`
                  } else {
                    if (res.message == 'needwait') {
                      this.$message.warning(this.$t('event.detail.components.eventButtonGroup.text13'))
                    } else {
                      if (res.data != null) {
                        this.needApprove(res.data)
                      } else {
                        this.$notify({
                          title: this.$t('common.base.error'),
                          message: res.message,
                          type: 'error'
                        });
                      }
                    }
                  }
                })
          } else {
            this.$notify({
              title: this.$t('common.base.error'),
              message: result.message,
              type: 'error'
            });
          }
        })
    },

    // 完成事件
    finishEvent() {
      this.$track.clickStat(this.$track.formatParams('FINISH_EVENT'));
      const params = {
        id: this.workEvent.id,
        flow: 'finish'
      }
      EventApi.eventCheckNotNullForCard(params)
        .then(result => {
          if(result.status == 0) {
            if(this.receiptFields && this.receiptFields.length > 0) {
              this.$emit('changeRightActiveTab', 'finishInfo')
              return
            }

            this.$confirm(this.$t('event.detail.components.eventButtonGroup.text14'), this.$t('common.base.toast'), {
              confirmButtonText: this.$t('common.base.makeSure'),
              cancelButtonText: this.$t('common.base.cancel'),
              type: 'warning',
            })
              .then(async () => {

                const params = {id: `${this.workEvent.id}`}
                // 判断是否有高级审批
                if (await this.checkNeedVipApprove('finish', params)) return;

                EventApi.eventFinish(params)
                    .then(res => {
                      if (res.status == 0) {
                        this.reloadTab();
                        window.location.href = `${this.$resourcePrefix}/event/view/${this.workEvent.id}`
                      } else {
                        if (res.message == 'needwait') {
                          this.$message.warning(this.$t('event.detail.components.eventButtonGroup.text13'))
                        } else {
                          if (res.data != null) {
                            this.needApprove(res.data)
                          } else {
                            this.$message.warning(res.message)
                          }
                        }
                      }
                    })
              })
              .catch(() => { });

          } else {
            this.$notify({
              title: this.$t('common.base.error'),
              message: result.message,
              type: 'error'
            });
          }
        })
    },

    onlySaveCusInfo() {
      this.cusInfoSaveTarget = 'update';
      const {isCusExist, isLmExist, isAddExist} = this.cusMatchMap

      if(isCusExist && isLmExist && isAddExist){
        // 全匹配上不做操作
      } else if (!isCusExist){
        // 客户没匹配上
        this.cusMatchDispVisible = true
      } else {
        // 客户匹配上了但是联系人或地址没匹配上
        this.$refs.saveToExistCustomerDialog.openDialog(this.workEvent.cusId)
      }
    },

    onlySaveLinkman() {
      this.$refs.eventSaveLinkman.openDialog();
    },
    /**
     * @description: 校验是否有可用工单类型
     */
    async verificationHaveTaskType() {
      const result = await EventApi.existValidTaskTypeForLoginUser()
      return result.data
    },

    /**
     * @description: 创建工单
     * @param {String} flow create 创建工单/finished 创建工单并完成事件
     */
    async convert2TaskNew(flow) {
      this.$track.clickStat(this.$track.formatParams('CREATE_TASK'));
      try {
        // 校验是否有可用工单类型 无可用工单类型 禁止事件转工单
        const haveTaskType = await this.verificationHaveTaskType()
        if(!haveTaskType) {
          this.$platform.notification({
            title: this.$t('event.detail.components.eventButtonGroup.text15'),
            type: 'error',
          })
          return 
        }
      } catch (error) {
        console.error(error)
      }

      this.creatTaskVisible = false
      this.toTaskFlow = flow
      this.cusInfoSaveTarget = 'convert';
      this.isConvert2Task = true

      const params = {
        id: this.workEvent.id,
        flow: 'convert2Task'
      }
      this.$emit('loadingPage', true)
      EventApi.eventCheckNotNullForCard(params)
        .then(async result => {
          if (result.status == 0) {

            const params = {eventId: `${this.workEvent.id}`}
            // 判断是否有高级审批
            if (await this.checkNeedVipApprove('allowConvert', params)) {
              this.$emit('loadingPage', false)
              return;
            };

            EventApi.eventCheck4ConvertApprove(params)
                .then(res => {
                  this.$emit('loadingPage', false)
                  if (res.status == 1) {
                    // TODO 需要审批判断改成errorCode
                    if (res.message == 'needwait') {
                      this.$message.warning(this.$t('event.detail.components.eventButtonGroup.text13'))
                    } else if (Number(res.errorCode) == 10003) {
                      this.needApprove(res.data)
                    }
                  } else {
                    const {isCusExist, isLmExist, isAddExist} = this.cusMatchMap

                    if (isCusExist && isLmExist && isAddExist) { // 全匹配上
                      // 跳转工单
                      let fromId = window.frameElement.getAttribute('id')
                      openAccurateTab({
                        type: PageRoutesTypeEnum.PageCreateTaskFromEvent,
                        params: `eventId=${this.workEvent.id}&flow=${flow}`,
                        fromId
                      })
                    } else if (!isCusExist) { // 客户没匹配上
                      this.cusMatchDispVisible = true
                    } else { // 客户匹配上了但是联系人或地址没匹配上
                      this.$refs.saveToExistCustomerDialog.openDialog(this.workEvent.cusId, this.isConvert2Task)
                    }
                  }
                })
          } else {
            this.$emit('loadingPage', false)
            this.$notify({
              title: this.$t('common.base.error'),
              message: result.message,
              type: 'error'
            });
          }
        })
        .finally(() => {
          this.isConvert2Task = false
        })
    },

    // 转派&手动分配
    editExecutor(type) {
      const params = {
        id: this.workEvent.id,
        flow: 'allot'
      }
      EventApi.eventCheckNotNullForCard(params)
        .then(result => {
          if(result.status == 0) {
            // 打开选择负责人弹窗
            let options = {
              title: this.$t('event.edit.text9'),
              seeAllOrg: true,
              max: 1,
              ...chooseExUser,
              mode: BaseSelectUserModeEnum.Filter
            };
            // 分配和转派传authKey 区分全部权限和团队权限
            options.authKey = 'CASE_ALLOT';
            this.$fast.select.multi.all(options).then(async chooseData => {
              if (chooseData.status == 0) {
                let executor = chooseData?.data?.users[0] || [];
                if (this.workEvent.executorId === executor.userId) {
                  this.$platform.notification({
                    title: this.$t('event.detail.components.eventButtonGroup.text16'),
                    type: 'error',
                  });
                  return
                }
                const params1 = {
                  id: `${this.workEvent.id}`,
                  executorId: executor.userId,
                  executorName: executor.displayName,
                }
                // 判断是否有高级审批
                if(await this.checkNeedVipApprove(type, params1)) return;

                EventApi.eventUpdateExecutor(params1).then(res => {
                  if (res.status === 0) {
                    // $("#executor").html(html +'&nbsp;&nbsp;<img src="/resource/images/edit.png" width="14px"/>');
                    window.location.href = `${this.$resourcePrefix}/event/view/${this.workEvent.id}`;
                  } else {
                    if (res.message == 'needwait') {
                      this.$message.warning(this.$t('event.detail.components.eventButtonGroup.text13'))
                    } else {
                      if (res.data != null) {
                        this.needApprove(res.data)
                      } else {
                        this.$notify({
                          title: this.$t('common.base.error'),
                          message: res.message,
                          type: 'error'
                        });
                      }
                    }
                  }
                }).catch(err => console.error(err))
              }
            })
              .catch(err => console.error(err))
          } else {
            this.$notify({
              title: this.$t('common.base.error'),
              message: result.message,
              type: 'error'
            });
          }
        })
    },

    // 判断是否需要高级审批
    async checkNeedVipApprove(action, params) {
      try {
        const result = await this.getVipApproveInfo(action, params);
        const { needVipApprove = false } = result
        needVipApprove && this.toNeedVipApprove(result);

        return needVipApprove;
      } catch (e) {
        throw new Error(e)
      } finally {
        this.$emit('loadingPage', false)
      }
    },

    // 获取高级审批信息
    async getVipApproveInfo(action, params) {
      try {
        const { success, result, message} = await checkEventNeedVipApprove({
          eventId: this.workEvent.id,
          eventTemplateId: this.workEvent.templateId,
          auto: action === 'allotAuto', // 自动分配需要传这个参数
          action: action === 'allotAuto' ? 'allot' : action,
          params,
        });
        if(!success) {
          this.$message.error(message);
          throw new Error(message);
        }
        return result;
      } catch (e) {
        throw new Error(e)
      }
    },

    // 打开高级审批弹框
    toNeedVipApprove(approval) {
      this.$refs.AdvancedApprovalDialogRef?.openDialog(approval);
    },

    // 自动分配
    async autoDispatch() {
      try {
        const confirm = await this.$confirm(this.$t('event.detail.components.eventButtonGroup.text17'), this.$t('common.base.toast'), {
          confirmButtonText: this.$t('common.base.makeSure'),
          cancelButtonText: this.$t('common.base.cancel'),
          type: 'warning',
        })
        if (!confirm) return;

        // 如果是自动分配校验事件自动分配规则是否可以匹配到负责人
        let checkAutoDispatchRes = await EventApi.checkAutoDispatch({eventId: this.workEvent.id});
        if(checkAutoDispatchRes.status !== 0 ) return this.$message.warning(checkAutoDispatchRes.message)

        const params = {
          id: this.workEvent.id,
          flow: 'allot'
        }
        EventApi.eventCheckNotNullForCard(params)
          .then(async result => {
            if (result.status == 0) {

              const params = {id: `${this.workEvent.id}`}
              // 判断是否有高级审批
              if (await this.checkNeedVipApprove('allotAuto', params)) return;

              EventApi.eventAutoDispatch({id: `${this.workEvent.id}`})
                  .then(res => {
                    if (res.status == 0) {
                      window.location.href = `${this.$resourcePrefix}/event/view/${this.workEvent.id}`;
                    } else {
                      // TODO 需要审批判断改成errorCode
                      if (res.message == 'needwait') {
                        this.$message.warning(this.$t('event.detail.components.eventButtonGroup.text13'))
                      } else if (Number(res.errorCode) == 10003) {
                        this.needApprove(res.data)
                      } else {
                        this.$notify({
                          title: this.$t('common.base.error'),
                          message: res.message,
                          type: 'error'
                        });
                      }
                    }
                  })
            } else {
              this.$notify({
                title: this.$t('common.base.error'),
                message: result.message,
                type: 'error'
              });
            }
          })   
      } catch (error) {
        console.log(error)
        
      }
    },

    // 审批
    approveThis(type) {
      this.$refs.eventApproveDialog.openDialog(type);
    },

    // 撤回审批
    offApprove() {
      this.$confirm(this.$t('common.base.tip.areYouSureYouWantWithdrawIt'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(() => {
          EventApi.approveOffApprove({apprId: `${this.unFinishedAppr.id }`})
            .then(res => {
              if(res.status == 0) {
                window.location.href = `${this.$resourcePrefix}/event/view/${this.workEvent.id}`
              } else {
                this.$notify({
                  title: this.$t('common.base.error'),
                  message: res.message,
                  type: 'error'
                });
              }
            })
        })
        .catch(() => { });
    },

    // 回退
    rollBack() {
      this.$refs.eventRollBackDialog.openDialog()
    },

    // 添加备注
    updataRemarks() {
      this.$emit('updataRemarks')
    //  this.$refs.eventAddRemarksDialog.openDialog()
    },

    // 复制事件
    copyEvent() {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
          type:PageRoutesTypeEnum.PageCreateEventByCopy,
          params:`id=${this.workEvent.id}&newTemplateId=${this.workEvent.templateId}`,
          closeNowPage:true,
          fromId
        })
      // location.href = `${this.$resourcePrefix}/event/copyEvent?id=${this.workEvent.id}&newTemplateId=${this.workEvent.templateId}`;
    },

    // 保存为新客户
    save2NewCustomer() {
      this.save2NewCustomerLoading = true
      let href = `${this.$resourcePrefix}/event/createCustomer?eventId=${this.workEvent.id}`;
      if(this.cusInfoSaveTarget == 'convert'){
        href = `${href}&goTo=createTask&flow=${this.toTaskFlow}`;
      }else{
        href = `${href}&goTo=eventView`;
      }
      window.location.href = href;
    },

    // 保存为现有客户
    save2ExistCustomer() {
      this.cusMatchDispVisible = false
      this.$refs.saveToExistCustomerDialog.openDialog(this.workEvent.cusId, this.isConvert2Task)
    },

    // 保存为现有客户 成功
    saveExistCusSuccess() {
      this.reloadTab();
      if(this.cusInfoSaveTarget == 'convert'){
        window.location.href = `${this.$resourcePrefix}/event/convent2Task/jump?eventId=${this.workEvent.id}&flow=${this.toTaskFlow}`;
      }else{
        window.location.href = `${this.$resourcePrefix}/event/view/${this.workEvent.id}`;
      }
    },

    refreshTab() {
      this.reloadTab();
      window.location.href = `${this.$resourcePrefix}/event/view/${this.workEvent.id}`;
    },
    // 打开邮件分享弹窗
    eShareClick(){
      this.$refs.EmailSharingDialog.openDialog()
    },
    // 判断是否显示邮件分享按钮
    async getMailSetting(){
      const {code, result} = await getMailSetting({type:'eventEmailShare'})
      if(code == 0 && result?.typeSwitch == 1){
        this.showEventEmailShare = true
      }
    },

		getBtnsTrackData(id, data) {
			return this.$track.formatParams(id, data, 'DETAIL_BTNS_GROUP')
		},
    amerPrintEvent(){
      let comName
      const { templateName,id } = this.workEvent

      if(AmerPrintEventTemplateListA.includes(templateName)) comName = 'AmerPrintTemplateA'

      if(AmerPrintEventTemplateListB.includes(templateName)) comName = 'AmerPrintTemplateB'

      if(AmerPrintEventTemplateListC.includes(templateName)) comName = 'AmerPrintTemplateC'

      
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventPrint,
        params: `comName=${comName}&id=${id}&templateName=${templateName}`,
      })
    }
  },
  watch: {
    vipApproveSetting: {
      handler() {
        this.buildApprovalButtonData();
      }
    }
  },
}
</script>

<style lang="scss" scoped>
ul {
  margin: 0;
  padding: 0;
  li {
    cursor: pointer;
    margin-bottom: 10px;
    padding: 5px;
    &:hover {
      background: $color-primary-light-6;
      color: #fff;
    }
    &:last-child {
      margin-bottom: 0;
    }
  }
}
.el-button {
  margin-left: 10px;
}
.icon-btn {
  vertical-align: middle;
  margin-left: 16px;
  font-size: 18px;
  color: #595959;
  cursor: pointer;
}
.has-been-deleted {
  color: red;
}
.base-modal-content {
  padding: 20px;
}
.event-btn-group {
  display: flex;
  flex: 1;
}
</style>
